#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/10/25 10:58
# @Author  : Tom_zc
# @FileName: upload_file.py
# @Software: PyCharm
import os
import sys
import time
import click
import logging

import yaml

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, "utils"))
PARENT_DIR = os.path.dirname(BASE_DIR)

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")

from utils.parse_params import parse_repo_info_by_webhook_payload, parse_payload_body
from utils.common import func_retry
from utils.obs_helper import ObsHelper


class PipeLineLogHelper:

    def __init__(self, ak, sk, obs_endpoint, obs_static_endpoint, obs_bucket_name, repo, pr_number):
        self.obs_helper = ObsHelper(ak, sk, obs_endpoint)
        self.obs_static_endpoint = obs_static_endpoint
        self.obs_bucket_name = obs_bucket_name
        self.repo = repo
        self.pr_number = pr_number

    def _get_bucket_key(self, filename, process, cur_date):
        date_str = time.strftime("%Y_%m_%d_%H_%M_%S", cur_date)
        return "{}/{}/{}_{}/{}".format(self.repo, self.pr_number, process, date_str, filename)

    @func_retry()
    def upload_obs(self, process, path_list):
        cur_date = time.localtime(time.time())
        for path in path_list:
            filename = os.path.basename(path)
            bucket_key = self._get_bucket_key(filename, process, cur_date)
            self.obs_helper.upload_file(self.obs_bucket_name, bucket_key, path)
            log_url = "{}/{}".format(self.obs_static_endpoint, bucket_key)
            logging.info("Uploaded the log, and url is:{}".format(log_url))


@click.command()
@click.option("--process", help='The progress of step')
def main(process):
    logging.info("=" * 20 + "start to upload the log to obs" + "=" * 20)
    ak = os.getenv("ak")
    sk = os.getenv("sk")
    obs_endpoint = os.getenv("obs_endpoint")
    obs_static_endpoint = os.getenv("obs_static_endpoint")
    obs_bucket_name = os.getenv("obs_bucket_name")

    if not all([ak, sk, obs_endpoint, obs_bucket_name, obs_static_endpoint]):
        logging.info("Lack of params, Please check.")
        sys.exit(-1)
    _, repo, _, pr_number, _ = parse_repo_info_by_webhook_payload()

    full_path = os.path.join(PARENT_DIR, "ci-repos", repo, "config.yaml")
    if os.path.exists(full_path):
        with open(full_path, "r") as f:
            config_obj = yaml.safe_load(f)
            path_list = config_obj.get(process)
    else:
        logging.info("The repo() is not in ci-repos.".format(repo))
        return
    if not path_list:
        logging.info("upload file get empty config about output log.")
        return

    pipeline_log_helper = PipeLineLogHelper(ak, sk, obs_endpoint, obs_static_endpoint, obs_bucket_name, repo, pr_number)
    pipeline_log_helper.upload_obs(process, path_list)

    logging.info("=" * 20 + "end to uploaded the obs" + "=" * 20)


if __name__ == '__main__':
    main()
